const gulp = require('gulp')
const spriterem = require('gulp.spritesmith')

const templateFunction = data => {
  const imageName = data.spritesheet.image.match(/[^\/\\]+$/)[0].replace(/\.\w+$/, '')
  const file = data.sprites[0].image.split('/')
  const filename = file[file.length - 1]
  const scssFunction = `
    @function px($px) {
      @return $px / 40 + rem;
    }
  `
  const shared = `
    %${imageName} {
      background-image: url(~@/images/${filename}?${(new Date()).getTime()});
      background-repeat: no-repeat;
      background-size: px(${data.spritesheet.width}) px(${data.spritesheet.height});
    }
  `

  const perSprite = data.sprites.map(sprite => {

    let pX = sprite.offset_x ? `px(${sprite.offset_x})` : 0
    let pY = sprite.offset_y ? `px(${sprite.offset_y})` : 0

    return '@mixin N { width: W; height: H; background-position: X Y; }'
      .replace('N', sprite.name)
      .replace('W', `px(${sprite.width})`)
      .replace('H', `px(${sprite.height})`)
      .replace('X', pX)
      .replace('Y', pY)
  }).join('\n')

  return scssFunction + '\n' + shared + '\n' + perSprite
}

gulp.task('sprite', async () => {
  await gulp.src('src/sprite/*').pipe(spriterem(
    {
      padding: 8,
      imgName: 'images/sprite.png',
      cssName: 'scss/_sprite.scss',
      algorithm: 'binary-tree',
      cssFormat: 'scss',
      cssTemplate: templateFunction
    }
  ))
    .pipe(gulp.dest('src/'))
})
